package org.sensornet2010.alpha;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.RecordControl;

public class SoundRecorder {

	private long duration	= 5000; //milliseconds
	
	public SoundRecorder(long acqTime){
		this.duration = acqTime;
	}
	
	public byte[] record(){
		byte[] sound = null;
		try {
			sound = this.recordSound();
			int len = sound.length;
		} catch (Exception e) {
			//DEBUG: e.printStackTrace();
			throw new RuntimeException("RECORDERROR=" + e.getClass()+ "=" + e.getMessage());
		}
		return sound;
	}
	private byte[] dummyRecord(){
		//byte[] sound = new byte[3];
		Date date = new Date();
		byte[] sound = date.toString().getBytes();
		return sound;
	}
	
	private byte[] recordSound() throws IOException, MediaException, InterruptedException {
		byte[] sound = null;
		Player p = Manager.createPlayer("capture://audio");
		p.realize();
		// Get the RecordControl, set the record stream,
		RecordControl rc = (RecordControl) p.getControl("RecordControl");
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		rc.setRecordStream(output);
		rc.startRecord();
		p.start();
		Thread.sleep(duration);
		rc.commit();
		p.close();
		sound = output.toByteArray();
		output.close();
		rc =null;
		p = null;
		output = null;
		System.gc();
		return sound;
	}

	
	
}
